package com.hxzy.controller.system;


import com.hxzy.common.constant.UserConstants;
import com.hxzy.common.core.controller.BaseController;
import com.hxzy.common.core.domain.AjaxResult;
import com.hxzy.common.core.domain.R;
import com.hxzy.common.core.domain.entity.SysDept;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.utils.StringUtils;
import com.hxzy.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/api")
@Api(tags = "部门管理API")
public class DeptController extends BaseController {

    @Autowired
    private ISysDeptService iSysDeptService;

    @ApiOperation(value = "查询所有部门信息")
    @GetMapping(value = "/list")
    public R list (SysDept dept) {
        List<SysDept> sysDepts = this.iSysDeptService.selectDeptList(dept);
        return R.okHasData(sysDepts);
    }


    @ApiOperation(value = "新增部门")
    @PostMapping(value = "/system/dept/add")
    public AjaxResult add (@RequestBody @Validated SysDept sysDept) {
        // 验证部门是否存在
        String unique = this.iSysDeptService.checkDeptNameUnique(sysDept);
        if (! unique.equals(UserConstants.UNIQUE)) {
            return AjaxResult.error("新增部门'" + sysDept.getDeptName() + "'失败，部门名称已存在");
        }
        sysDept.setCreateBy(getUsername());
        int i = this.iSysDeptService.inserDept(sysDept);
        return toAjax(i);
    }

    @ApiOperation(value = "根据id查询部门信息")
    @GetMapping(value = "/getId/{id}")
    public R getDeptById (@PathVariable Long id) {
        SysDept dept = this.iSysDeptService.selectDeptById(id);
        if (Objects.isNull(dept)) {
            return R.build(AckCode.NOT_FOUND_DATA);
        }
        return R.okHasData(dept);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/exclude/{deptId}")
    @ApiOperation(value = "查询部门列表（排除节点）")
    public AjaxResult excludeChild(@PathVariable Long deptId)
    {
        List<SysDept> depts = this.iSysDeptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return AjaxResult.success(depts);
    }

    @PutMapping(value = "/updateDept")
    @ApiOperation(value = "修改部门信息")
    public AjaxResult updateDept (@RequestBody @Validated SysDept sysDept) {

        if (this.iSysDeptService.checkDeptNameUnique(sysDept).equals(sysDept.getDeptName())) {
            return AjaxResult.error(sysDept.getDeptName() + "部门已存在");
        }
        if (sysDept.getParentId().equals(sysDept.getDeptId())) {
            return AjaxResult.error("上级部门不能是自己");
        }

        sysDept.setUpdateBy(getUsername());

        int i = this.iSysDeptService.updateDept(sysDept);
        return toAjax(i);
    }

    @DeleteMapping(value = "/remove/{deptId}")
    @ApiOperation(value = "根据id删除部门信息")
    public AjaxResult remove (@PathVariable @RequestBody Long deptId) {
        boolean boo = this.iSysDeptService.hasChildByDeptId(deptId);
        if (boo) {
            return AjaxResult.error("存在下级部门不允许删除");
        }
        boolean rel = this.iSysDeptService.checkDeptExistUser(deptId);
        if (rel) {
            return AjaxResult.error("部门存在账户,无法删除");
        }
        int i = this.iSysDeptService.deleteDeptById(deptId);
        return toAjax(i);
    }
    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public R treeselect(SysDept dept)
    {
        List<SysDept> sysDepts = iSysDeptService.selectDeptList(dept);
        return R.okHasData(iSysDeptService.buildMenuTreeSelect(sysDepts));
    }
}
